package com.jplus.framework.core;

import java.lang.annotation.Annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.framework.AppConstant;
import com.jplus.framework.bean.BeanHandle;
import com.jplus.framework.bean.annotation.Component;
import com.jplus.framework.util.ClassUtil;
import com.jplus.framework.util.FormatUtil;

/**
 * jplus加载器
 * 
 * @author Yuanqy
 *
 */
public class CoreLoader {

	private static final Logger logger = LoggerFactory.getLogger(CoreLoader.class);

	public static void init() {
		for (Class<?> cla : AppConstant.APP_LOAD_HANDLE) {
			logger.info("loadClass:{}", cla.getName());
			ClassUtil.loadClass(cla.getName());
		}
		BeanHandle.clearCache();
		logger.info("=============== Jplus Is Loading Finish ~ o(*≧▽≦)ツ ~=============");
		doInitMethod(Component.class);
	}

	// =======================================================
	private static void doInitMethod(Class<? extends Annotation> cla) {
		try {
			for (Class<?> cls : BeanHandle.beanAround) {
				if (cls.isAnnotationPresent(cla)) {
					String initM = "";
					if (cla.equals(Component.class))
						initM = ((Component) cls.getAnnotation(cla)).initMethod();
					if (!FormatUtil.isEmpty(initM)) {
						Object obj = BeanHandle.getBean(cls);
						if (obj == null)
							obj = cls.newInstance();
						cls.getMethod(initM, new Class<?>[] {}).invoke(obj, new Object[] {});
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
